<?php
/**
 * Note:     [Description]
 * Author:   longhui.huang <1592328848@qq.com>
 * DateTime: 2024/3/7 14:35
 */
declare(strict_types=1);


namespace App\Cache;


use App\Bean\JwtUserBean;
use App\Model\UserModel;
use App\Utility\Redis\RedisUtil;

class UserCache extends BaseCache
{
    public const CACHE_KEY = 'user-login-cache:';

    /**
     * 返回用户缓存
     *
     * @param string $username
     *
     * @return JwtUserBean|null
     * @throws \App\Utility\Redis\Exception\RedisException
     * @throws \EasySwoole\ORM\Exception\Exception
     */
    public function getUserCache(string $username)
    {
        if ($username) {
            $json = RedisUtil::get(self::CACHE_KEY . $username);
            if ($json) {
                $arr         = json_decode($json, true);
                $user        = $arr['user'];
                $userModel   = new UserModel($user);
                $arr['user'] = $userModel;
                return new JwtUserBean($arr);
            }
        }

        return null;
    }

    /**
     * 添加缓存到Redis
     *
     * @param string      $username 用户名
     * @param JwtUserBean $user
     *
     * @throws \App\Utility\Redis\Exception\RedisException
     */
    public function addUserCache(string $username, JwtUserBean $user)
    {
        if ($username) {
            // 添加数据, 避免数据同时过期
            $time = config('app.login.user-cache.idle-time') + random_int(900, 1800);
            RedisUtil::setex(self::CACHE_KEY . $username, $time, json_encode($user));
        }
    }

    /**
     * 清理用户缓存信息
     * 用户信息变更时
     *
     * @param string $username 用户名
     *
     * @throws \App\Utility\Redis\Exception\RedisException
     */
    public function cleanUserCache(string $username)
    {
        if ($username) {
            // 清除数据
            RedisUtil::del(self::CACHE_KEY . $username);
        }
    }
}
